package com.hitfm.iplay.util;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.apache.http.protocol.HTTP;
import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.StrictMode;
import android.util.Log;

public class NetOperation {

	public static String httpGetMp3URL(String singerString, String titleString) {
		String mp3URL = "";
		try {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
					.penaltyLog().penaltyDeath().build());
			URL url = new URL("http://box.zhangmen.baidu.com/x?op=12&count=1&title=" + URLEncoder.encode(titleString, HTTP.UTF_8)
					+ "$$" + URLEncoder.encode(singerString, HTTP.UTF_8) + "$$$");
			URLConnection con = url.openConnection();

			String result = "http status code: " + ((HttpURLConnection) con).getResponseCode() + "\n";
			InputStream is = con.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			ByteArrayBuffer bab = new ByteArrayBuffer(32);
			int current = 0;
			while ((current = bis.read()) != -1) {
				bab.append((byte) current);
			}
			result += EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);

			bis.close();
			is.close();
			Log.i("test", result);
			String preurlString = result.substring(result.indexOf("http://"), result.indexOf("]]></encode>"));
			String prefix = preurlString.substring(0, preurlString.lastIndexOf("/") + 1);
			String sufurlString = result.substring(result.indexOf("<decode><![CDATA["), result.indexOf("]]></decode>"));
			String suffix = sufurlString.substring("<decode><![CDATA[".length(), sufurlString.length());
			mp3URL = prefix + suffix;
		} catch (Exception e) {
			return "";
		}
		return mp3URL;
	}
}
